package com.cet.spring_batch_study.jobs.endOfDay;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepExecutionListener;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;

/**
 * @author NSOC
 */
@Configuration
public class EndOfDayJob {

    @Bean
    public Job endOfDay(JobRepository jobRepository, Step step1, Step step2) {
        return new JobBuilder("endOfDay", jobRepository)
                .validator(new EndOfDayJobParameterValidator())
//                .incrementer(new LoopTimesIncrementer())
                .incrementer(new RunIdIncrementer())
                .start(step1)
                .next(step2)
                .build();
    }

    @Bean
    public Step step1(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
        return new StepBuilder("step1", jobRepository)
                .tasklet((contribution, chunkContext) -> RepeatStatus.FINISHED, transactionManager)
                .build();
    }

    @Bean
    public Step step2(JobRepository jobRepository, PlatformTransactionManager transactionManager,
                      StepExecutionListener endOfDayStepExecutionListener) {
        return new StepBuilder("step2", jobRepository)
                .tasklet(new LongTimeElapseTaskletStep(), transactionManager)
                .startLimit(10)
                .allowStartIfComplete(true)
                .listener(endOfDayStepExecutionListener)
                .build();
    }

    @Bean
    public StepExecutionListener endOfDayStepExecutionListener() {
        return  new EndOfDayStepExecutionListener();
    }
}
